/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#include <string>
#include <vector>
#include <pthread.h>
#include <jni.h>
#include <android/log.h>
#include "Log.h"
#include <iostream>
#include "WebTask.h"

typedef std::vector<std::string> StringList;

JNIEnv* env;
jclass jniHelperClz;
jobject jniHelperObj;

/*分割String*/
StringList splitstr(const std::string& str, char tag)
{
    StringList stringList;
    std::string subStr;

    for(char i : str)
    {
        if(tag == i)
        {
            if(!subStr.empty())
            {
                stringList.push_back(subStr);
                subStr.clear();
            }
        }
        else
        {
            subStr.push_back(i);
        }
    }

    if(!subStr.empty())
    {
        stringList.push_back(subStr);
    }

    return stringList;
}


extern "C" {


__attribute ((visibility ("default")))
JNIEXPORT void JNICALL Java_com_example_mbedtlscurl_JavaToNative_CpostAsync(JNIEnv *env, jobject instance, jstring mUrl, jstring msg_, jstring jUserAgent, jboolean isSingle){

    std::string mString;
    std::string url2 = env->GetStringUTFChars(mUrl, nullptr);
    std::string message = env->GetStringUTFChars(msg_, nullptr);
    std::string UserAgent ;
    if(jUserAgent!=nullptr){
        UserAgent = env->GetStringUTFChars(jUserAgent, nullptr);
    }

    WebTask task;
    task.SetUrl(url2.c_str());
    task.SetConnectTimeout(5);
    task.AddHeader("Content-Type","text/plain");
    if(!UserAgent.empty()){
        task.setUserAgent(const_cast<char *>(UserAgent.c_str()));
    }else{
        task.setUserAgent(nullptr);
    }


    if (isSingle){
        task.data = message;
    } else{
        char tag = '&';
        char tag2 = '=';
        StringList list = splitstr(message, tag);
        for (const auto& string : list) {
            StringList string2 = splitstr(string, tag2);
            task.AddPostString(string2[0].c_str(), string2[1].c_str());
        }

    }
    task.DoGetString();
    int code = task.WaitTaskDone();
    if (code == CURLE_OK) {
        //请求服务器成功
        mString = task.GetResultString();
        LOGI("C++返回的是：%s\n", mString.c_str());
    } else{
        LOGI("请求失败返回值：%d",code);
        mString = "出错了";
    }

    jmethodID Func = (*env).GetMethodID(jniHelperClz,"postCallBack","(ILjava/lang/String;)V");
    jstring javaMsg = (*env).NewStringUTF(mString.c_str());
    (*env).CallVoidMethod(jniHelperObj, Func, code, javaMsg);
    (*env).DeleteLocalRef(javaMsg);
}

__attribute ((visibility ("default")))
JNIEXPORT jstring JNICALL Java_com_example_mbedtlscurl_JavaToNative_Cpost(JNIEnv *env, jobject instance, jstring mUrl, jstring msg_, jstring jUserAgent, jboolean isSingle){

    std::string mString;
    std::string url2 = env->GetStringUTFChars(mUrl, nullptr);
    std::string message = env->GetStringUTFChars(msg_, nullptr);
    std::string UserAgent ;
    if(jUserAgent!=nullptr){
        UserAgent = env->GetStringUTFChars(jUserAgent, nullptr);
    }

    LOGI("%s",url2.c_str());

    WebTask task;
    task.SetUrl(url2.c_str());
    task.SetConnectTimeout(5);
    task.AddHeader("Content-Type","text/plain");
    if(!UserAgent.empty()){
        task.setUserAgent(const_cast<char *>(UserAgent.c_str()));
    }else{
        task.setUserAgent(nullptr);
    }

    if(isSingle){
        task.data = message;
    } else{
        char tag = '&';
        char tag2 = '=';
        StringList list = splitstr(message, tag);
        for (const auto& string : list) {
            StringList string2 = splitstr(string, tag2);
            task.AddPostString(string2[0].c_str(), string2[1].c_str());
        }
    }


    task.DoGetString();
    int code = task.WaitTaskDone();
    if (code == CURLE_OK) {
        //请求服务器成功
        mString = task.GetResultString();
        LOGI("C++返回的是：%s\n", mString.c_str());
    } else{
        LOGI("请求失败返回值：%d",code);
        mString = "出错了";
    }
    jstring javaMsg = (*env).NewStringUTF((std::to_string(code)+"="+mString).c_str());
    return javaMsg;
}

__attribute ((visibility ("default")))
JNIEXPORT void JNICALL Java_com_example_mbedtlscurl_JavaToNative_CgetAsync(JNIEnv *env, jobject instance, jstring mUrl, jstring jUserAgent){

    std::string mString;
    std::string url = env->GetStringUTFChars(mUrl, nullptr);
    std::string UserAgent ;
    if(jUserAgent!=nullptr){
        UserAgent = env->GetStringUTFChars(jUserAgent, nullptr);
    }

    WebTask webTask;
    webTask.SetUrl(url.c_str());
    webTask.SetConnectTimeout(5);
    webTask.AddHeader("Content-Type","text/plain");
    if(!UserAgent.empty()){
        webTask.setUserAgent(const_cast<char *>(UserAgent.c_str()));
    }else{
        webTask.setUserAgent(nullptr);
    }

    webTask.DoGetString();
    int code = webTask.WaitTaskDone();
    if (code == CURLE_OK) {
        //请求服务器成功
        mString = webTask.GetResultString();
        LOGI("C++返回的是：%s\n", mString.c_str());
    } else{
        LOGI("请求失败返回值：%d",code);
        mString = "出错了";
    }

    jmethodID Func = (*env).GetMethodID(jniHelperClz,"getCallBack","(ILjava/lang/String;)V");
    jstring javaMsg = (*env).NewStringUTF(mString.c_str());
    (*env).CallVoidMethod(jniHelperObj, Func, code, javaMsg);
    (*env).DeleteLocalRef(javaMsg);
}

__attribute ((visibility ("default")))
JNIEXPORT jstring JNICALL Java_com_example_mbedtlscurl_JavaToNative_Cget(JNIEnv *env, jobject instance, jstring mUrl, jstring jUserAgent){

    std::string mString;
    std::string url = env->GetStringUTFChars(mUrl, nullptr);
    std::string UserAgent ;
    if(jUserAgent!=nullptr){
        UserAgent = env->GetStringUTFChars(jUserAgent, nullptr);
    }

    WebTask webTask;
    webTask.SetUrl(url.c_str());
    webTask.SetConnectTimeout(5);
    webTask.AddHeader("Content-Type","text/plain");
    if(!UserAgent.empty()){
        webTask.setUserAgent(const_cast<char *>(UserAgent.c_str()));
    }else{
        webTask.setUserAgent(nullptr);
    }

    webTask.DoGetString();
    int code = webTask.WaitTaskDone();
    if (code == CURLE_OK) {
        //请求服务器成功
        mString = webTask.GetResultString();
        LOGI("C++返回的是：%s\n", mString.c_str());
    } else{
        LOGI("请求失败返回值：%d",code);
        mString = "出错了";
    }

    jstring javaMsg = (*env).NewStringUTF((std::to_string(code)+"="+mString).c_str());
    return javaMsg;
}
}
